/**
 * Copyright (C) 2008 Happy Fish / YuQing
 * FastDFS Java Client may be copied only under the terms of the GNU Lesser
 * General Public License (LGPL).
 * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
 */
package org.csource.fastdfs.test;

import java.io.FileOutputStream;
import java.io.IOException;

import org.csource.fastdfs.DownloadCallback;

/**
 * DowloadCallback test
 * 
 * @author Happy Fish / YuQing
 * @version Version 1.3
 */
public class DownloadFileWriter implements DownloadCallback {
    private String           filename;
    private FileOutputStream out           = null;
    private long             current_bytes = 0;

    public DownloadFileWriter(String filename) {
        this.filename = filename;
    }

    @Override
    public int recv(long file_size, byte[] data, int bytes) {
        try {
            if (out == null) {
                out = new FileOutputStream(filename);
            }
            out.write(data, 0, bytes);
            current_bytes += bytes;
            if (current_bytes == file_size) {
                out.close();
                out = null;
                current_bytes = 0;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    protected void finalize() throws Throwable {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}
